<template>
  <basic-dialog
    width="60%"
    title="新增多音字"
    :visible="visible"
  >
    <el-form
      inline
      ref="formData"
      :model="formData"
      :rules="formRules"
      :labelWidth="labelWidth"
    >
      <el-form-item prop="polyphone" label="多音字">
        <el-input v-model="formData.polyphone" :maxlength="1" show-word-limit />
      </el-form-item>
      <el-form-item prop="defaultPinyin" label="拼音">
        <el-input v-model="formData.defaultPinyin" :maxlength="1" show-word-limit />
      </el-form-item>
    </el-form>
    <el-row slot="ft" type="flex" justify="end">
      <el-button
        type="primary"
        :loading="saveLoading"
        @click="handleSave"
      >保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import { CN_CHARACTERS, EN_CHARACTERS } from '@/constants/regExp';
import { batchAddPolyphoneService } from '@/api/basics/aliasManage/polyphoneManage';
export default {
  components: { BasicDialog },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    labelWidth: {
      type: String,
      default: '80px'
    }
  },
  data () {
    return {
      formData: {
        polyphone: '',
        defaultPinyin: ''
      },
      formRules: {
        polyphone: [
          { required: true, message: '汉字不能为空', trigger: 'blur' },
          { pattern: CN_CHARACTERS, message: '只能输入汉字', trigger: ['blur', 'change'] }
        ],
        defaultPinyin: [
          { required: true, message: '拼音不能为空', trigger: 'blur' },
          { pattern: EN_CHARACTERS, message: '只能输入英文', trigger: ['blur', 'change'] }
        ]
      },
      saveLoading: false
    }
  },
  methods: {
    handleCancel () {
      this.$emit('update:visible', false);
    },
    handleSave () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          const saveParamList = [{ ...this.formData }];
          this.savePolyphone(saveParamList);
        } else {
          this.$message.warning('校验不通过，请检查填写内容');
        }
      });
    },
    async savePolyphone (saveParamList) {
      const data = { saveParamList };
      const loadingFn = state => { this.saveLoading = state };
      const retStatus = await batchAddPolyphoneService(data, loadingFn);
      if (retStatus) {
        this.$message.success('新增多音字成功');
        this.$emit('getResult', true);
        this.$emit('update:visible', false);
        this.$refs.formData.resetFields();
      }
    }
  }
}
</script>
